package edu.sdbi.judge.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import edu.sdbi.judge.domain.vo.JsonResult;
import edu.sdbi.judge.domain.vo.StudentResult;
import edu.sdbi.judge.mapper.DailyVisitsMapper;
import edu.sdbi.judge.service.GetJudgeIpResultService;
import edu.sdbi.judge.util.ErrorUtil;
import edu.sdbi.judge.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Order(14)
@Service
public class Judge_14 implements GetJudgeIpResultService {
    @Autowired
    private HttpUtil httpUtil;
    @Autowired
    private DailyVisitsMapper dailyVisitsMapper; // 注入Mapper


    @Value("${test.newsId:1}")
    private String newsID;
    @Value("${test.startDate:2025-06-14}")
    private String startDate;

    @Value("${test.endDate:2025-06-14}")
    private String endDate;
    @Value("${test.startDate:2025-06-15}")
    private String startDate2;

    @Value("${test.endDate:2025-06-15}")
    private String endDate2;

    // 预期的每日访问量数据（根据测试数据配置）
//    private static final Map<String, Integer> EXPECTED_VISITS;
//
//    static {
//        Map<String, Integer> map = new HashMap<>();
//        map.put("2025-06-14", 164);
//        map.put("2025-06-15", 172);
//        EXPECTED_VISITS = Collections.unmodifiableMap(map);
//    }
    @Override
    public StudentResult getJudgeIpResult(String ip) {
        StudentResult studentResult = new StudentResult();
        studentResult.setItemNumber("14");

        try {
            // 直接使用配置中的newsID，无需数据库查询
            String url = "http://" + ip + "/statistics/dayVisits";

            // 封装请求参数，使用配置中的newsID
            Map<String, String> params = new HashMap<>();
            params.put("newsID", newsID);
            params.put("newID", newsID);
            params.put("startDate", startDate);
            params.put("endDate", endDate2);

            // 发送HTTP请求
            String resultStr = httpUtil.doGet(url, null, params);
            studentResult.setResult(resultStr);

            // 验证返回结果
            JsonResult jsonResult = JSONObject.parseObject(resultStr, JsonResult.class);
            if (jsonResult.getCode() == 200) {
                Integer dailyVisits = dailyVisitsMapper.getDailyVisitsByRange(startDate, endDate + " 23:59:59");
                Integer dailyVisits2 = dailyVisitsMapper.getDailyVisitsByRange(startDate2, endDate2 + " 23:59:59");
                // 解析返回的data部分
                JSONArray dataArray = JSONObject.parseArray(jsonResult.getData().toString());

                //@SuppressWarnings("unchecked")
                List<Map> dataList = dataArray.toJavaList(Map.class);
                // 从数据库获取预期数据
                List<Map> dataList2 = new ArrayList<>();
                Map expectedData = new HashMap<>();
                Map expectedData2 = new HashMap<>();
                expectedData.put("date", "2025-06-14");
                expectedData.put("visitsCount", dailyVisits);
                expectedData2.put("date", "2025-06-15");
                expectedData2.put("visitsCount", dailyVisits2);
                dataList2.add(expectedData);
                dataList2.add(expectedData2);
                if (validateResponseData(dataList, dataList2)) {
                    studentResult.setScore(2.0);
                    studentResult.setComment("测试通过：返回数据格式和内容正确");
                } else {
                    studentResult.setScore(0.0);
                    studentResult.setComment("返回数据格式或内容不符合要求");
                }
            } else {
                studentResult.setScore(0.0);
                studentResult.setComment("接口返回错误码：" + jsonResult.getCode());

            }
        } catch (Exception e) {
            e.printStackTrace();
            studentResult.setResult(ErrorUtil.stackTraceToString(e));
            studentResult.setScore(0.0);
            studentResult.setComment("执行测试时发生异常：" + e.getMessage());
        }
        return studentResult;
    }

    // 从数据库获取预期数据
    private Map<String, Integer> getExpectedDataFromDb() {
        Map<String, Integer> expectedData = new HashMap<>();

        try {
            // 调用Mapper方法获取数据库中的实际数据
            Integer dailyVisits = dailyVisitsMapper.getDailyVisitsByRange(startDate, endDate);
            Integer dailyVisits2 = dailyVisitsMapper.getDailyVisitsByRange(startDate2, endDate2);
            System.out.println(dailyVisits);
            System.out.println(dailyVisits2);

            // 转换为日期->访问量的映射

            System.out.println("从数据库获取的预期数据: " + expectedData);
        } catch (Exception e) {
            // 处理异常，例如记录日志
            System.err.println("获取数据库数据失败: " + e.getMessage());
            e.printStackTrace();
        }

        return expectedData;
    }

    private boolean validateResponseData(List<Map> dataList, List<Map> expectedData) {
        // 检查数据是否为空
        if (dataList == null || dataList.isEmpty()) {
            return false;
        }
        // 检查数据条数是否与预期一致
        if (dataList.size() != expectedData.size()) {
            System.out.println("返回数据条数不匹配。预期: " + expectedData.size() + ", 实际: " + dataList.size());
            return false;
        }

        // 逐条验证日期和访问量是否与预期一致
        Map dayData = dataList.get(0);
        String date = (String) dayData.get("date");
        Integer visitsCount = (Integer) dayData.get("visitsCount");
        Map dayData1 = expectedData.get(0);
        String date1 = (String) dayData.get("date");
        Integer visitsCount1 = (Integer) dayData1.get("visitsCount");
        if (date == null || visitsCount == null || !date.equals(date1) || !visitsCount.equals(visitsCount1)) {
            return false;
        }
        Map dayData2 = dataList.get(1);
        String date2 = (String) dayData.get("date");
        Integer visitsCount2 = (Integer) dayData2.get("visitsCount");
        Map dayData3 = expectedData.get(1);
        String date3 = (String) dayData.get("date");
        Integer visitsCount3 = (Integer) dayData3.get("visitsCount");
        if (date2.isEmpty() || visitsCount2 == null || !date3.equals(date2) || !visitsCount2.equals(visitsCount3)) {
            return false;
        }

        return true;
    }
}
